﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Classified.Data;
using Classified.Data.Repositories;
using Classified.Domain.Entities;
using Classified.Service;
using Classified.Web.Helpers;
using Classified.Web.Models;
using Classified.Web.Services;
using Classified.Web.net.webservicex.www;
using MvcPaging;

namespace Classified.Web.Controllers
{
    public class ClassifiedAdsController : Controller
    {
        //
        // GET: /ClassifedAds/
        private readonly IClassifiedAdCategoryRepository _classifiedAdCategoryRepository;
        private readonly IClassifiedRepository _classifiedRepository;
        private readonly ISecurityService _securityService;
        private readonly IClassifiedPictureRepositories _classifiedPictureRepositories;
        private readonly ILocationRepository _locationRepository;
        private readonly IClassifiedCommentRepository _classifiedCommentRepository;
        private readonly IOderDetailRepositories _oderDetailRepositories;
        private readonly ICategoryAttributeRepository _categoryAttributeRepository;
        private readonly IAttributeValueRepository _attributeValueRepository;
        private IFormsAuthenticationService _formsAuthenticationService;
        private readonly IClasifiedAttributeRepository _clasifiedAttributeRepository;
        private readonly ITopViewRepositories _topViewRepositories;
        private IEmailVerificationlLogRepositories _verificationlLogRepositories;
        private ICountryRepository _countryRepository { get; set; }
        private ICurrencyRepository _currencyRepository { get; set; }
        private IMessageInfoRepositories _messageInfoRepositories { get; set; }
        private readonly string domainName = ConfigurationManager.AppSettings["domainName"];
        private readonly string cookieDomainName = ConfigurationManager.AppSettings["cookieDomainName"];
        private readonly string AdminEmail = ConfigurationManager.AppSettings["Adsx24NotificationEmail"];
        private readonly string EmailFrom = ConfigurationManager.AppSettings["EmailFrom"];
        public string CategoriesId = "";
        public string LocationsId = "";

        private readonly IQueuedEmailRepositories _queuedEmailRepositories;
        public ClassifiedAdsController(IClassifiedAdCategoryRepository classifiedAdCategoryRepository,
            ITopViewRepositories topViewRepositories,
                                       IClassifiedRepository classifiedRepository,
                                       ISecurityService securityService,
                                       IClassifiedPictureRepositories classifiedPictureRepositories,
                                       ILocationRepository locationRepository,
                                       IClassifiedCommentRepository classifiedCommentRepository,
            IClasifiedAttributeRepository clasifiedAttributeRepository,
            IOderDetailRepositories oderDetailRepositories,
            ICategoryAttributeRepository categoryAttributeRepository,
            IAttributeValueRepository attributeValueRepository,
            IQueuedEmailRepositories queuedEmailRepositories,
            ICountryRepository countryRepository,
            ICurrencyRepository currencyRepository,
            IMessageInfoRepositories messageInfoRepositories,
            IEmailVerificationlLogRepositories verificationlLogRepositories)
        {
            _classifiedAdCategoryRepository = classifiedAdCategoryRepository;
            _classifiedRepository = classifiedRepository;
            _securityService = securityService;
            _classifiedPictureRepositories = classifiedPictureRepositories;
            _locationRepository = locationRepository;
            _classifiedCommentRepository = classifiedCommentRepository;
            _oderDetailRepositories = oderDetailRepositories;
            _categoryAttributeRepository = categoryAttributeRepository;
            _attributeValueRepository = attributeValueRepository;
            _clasifiedAttributeRepository = clasifiedAttributeRepository;
            _queuedEmailRepositories = queuedEmailRepositories;
            _topViewRepositories = topViewRepositories;
            _countryRepository = countryRepository;
            _currencyRepository = currencyRepository;
            _verificationlLogRepositories = verificationlLogRepositories;
            _messageInfoRepositories = messageInfoRepositories;
            _formsAuthenticationService = new FormsAuthenticationService(new HttpContextWrapper(System.Web.HttpContext.Current));
        }



        public ActionResult Index()
        {
            var data = _classifiedAdCategoryRepository.GetMany(c => c.IsActive).OrderBy(c => c.Name);
            return View(data);
        }
        [OutputCache(Duration = 60)]
        public PartialViewResult HomePageCategories()
        {

            var data = _classifiedAdCategoryRepository.GetMany(c => c.IsActive).OrderBy(c => c.Name);

            return PartialView(data);
        }
        public ActionResult RelatedAds(int id)
        {
            BuildCategoryIdPath(id);
            GetLcationId();
            if (CountryId != "")
            {
                BuldLocationByCountryId(CountryId);
            }
            if (curlocationId != "")
            {
                BuildLocationIdPath(curlocationId);
            }
            var classifieds = _classifiedRepository.GetClassifiedAdsByLocationCategoryAttributes(CategoriesId, "", LocationsId);
            var rnd = new Random();
            classifieds = classifieds.Distinct().OrderByDescending(i => i.IsEnhanced).ToList();
            var rndlist = classifieds.OrderBy(x => rnd.Next()).Take(30).ToList();
            return PartialView(rndlist);
        }

        public ActionResult FeaturedList()
        {
            var location = string.Empty;
            var data = new List<ClassifiedAd>();
            var currentHost = Request.Url.Host;
            var sub = currentHost.Split('.')[0];

            if (sub == "www" || sub == domainName || sub == "mail")
            {
            }
            else
            {
                location = sub;
            }

            var rnd = new Random();

            if (!string.IsNullOrEmpty(location))
            {


                var list = _classifiedRepository.GetMany(x => x.IsEnhanced).ToList();
                data = new List<ClassifiedAd>();
                foreach (var item in list)
                {
                    var name = location;
                    if (location.Contains("-"))
                    {
                        name = location.Replace("-", " ");
                    }


                    var a = item.Locations.FirstOrDefault(x => x.UrlName.ToLower() == location.ToLower() || x.Countries.Name.ToLower() == name);
                    if (a != null)
                        data.Add(item);
                }

            }
            else
            {
                data = _classifiedRepository.GetMany(x => x.IsEnhanced).ToList();
            }
            var rndlist = data.OrderBy(x => rnd.Next()).Take(6).ToList();
            if (rndlist != null)
            {


                foreach (var classifiedAd in rndlist)
                {


                    var topview = new TopView()
                                      {
                                          ClassifiedId = classifiedAd.Id,
                                          IsFeaturePost = true,
                                          CreatedDate = DateTime.UtcNow


                                      };
                    _topViewRepositories.Add(topview);
                }
            }
            else
            {
                rndlist = new List<ClassifiedAd>();
            }
            return PartialView(rndlist);
        }
        [HttpPost]
        public ActionResult LoadCategoryChild(string id)
        {
            var categoryId = Convert.ToInt32(id);
            var categoryparent = _classifiedAdCategoryRepository.GetMany(x => x.ParentCategoryId == categoryId).ToList();
            var data = categoryparent.Select(i => new ClassifiedCategory
            {
                Id = i.Id,
                Name = i.Name
            });
            return Json(new { list = data, guid = Guid.NewGuid() }, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public ActionResult LoadLocationByLocationId(string id)
        {

            var parentId = Convert.ToInt32(id);
            var locationparent = _locationRepository.GetMany(x => x.ParentId == parentId).ToList();
            var data = locationparent.Select(i => new ClassifiedCategory());
            if (parentId == 0)
            {
                locationparent = new List<Location>();
            }

            data = locationparent.Select(i => new ClassifiedCategory
            {
                Id = i.Id,
                Name = i.Name
            });

            return Json(new { list = data, guid = Guid.NewGuid() }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult LoadLocationByCountry(string id)
        {
            if (id == "")
            {
                id = "0";
            }

            var countryId = Convert.ToInt32(id);
            var currency_ISO = "";
            var currency = _currencyRepository.GetById(x => x.CountryId == countryId);
            var locationparent = _locationRepository.GetMany(x => x.CountryId == countryId && x.ParentId == 0).ToList();
            var data = locationparent.Select(i => new ClassifiedCategory
            {
                Id = i.Id,
                Name = i.Name
            });
            if (currency != null)
            {
                currency_ISO = currency.ISO_Code;
            }
            return Json(new { locationlist = data, ISO = currency_ISO, guid = Guid.NewGuid() }, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public PartialViewResult ClassifiedImageGallery(int id)
        {
            var data =
                _classifiedPictureRepositories.GetMany(x => x.ClassifiedId == id && x.Deleted == false).
                    OrderByDescending(x => x.Id).ToList();
            return PartialView(data);
        }

        public ActionResult Details(int id, string seName)
        {
            var data = _classifiedRepository.GetById(id);
            ViewBag.CountID = _topViewRepositories.GetMany(x => x.ClassifiedId == data.Id).Count();
            var cookieValue = data.Id.ToString();
            var topview = new TopView
                              {
                                  ClassifiedId = data.Id,
                                  IsFeaturePost = false,
                                  CreatedDate = DateTime.UtcNow

                              };
            _topViewRepositories.Add(topview);




            var cookielist = new StringBuilder();
            if (HttpContext.Request.Cookies.AllKeys.Contains("RecentView"))
            {
                HttpCookie cookie1 = HttpContext.Request.Cookies["RecentView"];
                cookielist.Append(cookie1.Value);
                cookielist.Append("|" + cookieValue);
            }
            else
            {
                cookielist.Append(cookieValue);
            }

            var cookie2 = new HttpCookie("RecentView", cookielist.ToString());
            Response.AppendCookie(cookie2);

            if (data == null)
            {
                return RedirectToAction("Index");
            }
            return View(data);
        }

        [HttpPost]
        public ActionResult AdcategoriesHierarchy(string parentId, string id)
        {

            var categoryId = Convert.ToInt32(parentId);
            var categoryparent = _classifiedAdCategoryRepository.GetMany(x => x.ParentCategoryId == categoryId).ToList();
            var data = new SelectList(categoryparent, "Id", "Name", id);
            var category = _classifiedAdCategoryRepository.GetById(x => x.Id == categoryId);
            var data1 = new ClassifiedCategory();
            var guid = Guid.NewGuid();
            if (category != null)
            {
                data1 = new ClassifiedCategory
                {
                    ParentCategoryId = category.ParentCategoryId,
                    Id = category.Id,

                };


            }
            else
            {
                data1 = null;
            }

            return Json(new { selctlist = data, categoryparent = data1, Guid = guid }, JsonRequestBehavior.AllowGet);
        }
        public string CountryId = "";
        public string curlocationId = "";
        public void GetLcationId()
        {

            var name = getLocation();
            var data = _locationRepository.GetById(x => x.UrlName.ToLower() == name);
            if (data == null)
            {

                var countryname = name.Replace("-", " ");
                var countries = _countryRepository.GetById(x => x.Name.ToLower() == countryname);
                if (countries != null)
                {
                    CountryId = countries.Id.ToString();
                }
            }
            else
            {
                curlocationId = data.Id.ToString();
            }


        }
        public void BuldLocationByCountryId(string countryId)
        {
            var id = int.Parse(countryId);
            if (LocationsId == "")
            {
                LocationsId = countryId;
            }
            var location = _locationRepository.GetMany(x => x.CountryId == id);
            foreach (var i in location)
            {
                LocationsId += "," + i.Id;
                var location_id = Convert.ToString(i.Id);
                BuldLocationByCountryId(location_id);
            }
        }
        public void BuildLocationIdPath(string loc_Id)
        {
            var id = int.Parse(loc_Id);
            if (LocationsId == "")
            {
                LocationsId = loc_Id;
            }
            var location = _locationRepository.GetMany(x => x.ParentId == id);
            foreach (var i in location)
            {
                LocationsId += "," + i.Id;
                var location_id = Convert.ToString(i.Id);
                BuildLocationIdPath(location_id);
            }
        }
        public void BuildCategoryIdPath(int parentId)
        {
            if (CategoriesId == "")
            {
                CategoriesId = parentId.ToString();
            }

            var categories = _classifiedAdCategoryRepository.GetMany(x => x.ParentCategoryId == parentId);
            foreach (var category in categories)
            {
                CategoriesId += "," + category.Id;
                BuildCategoryIdPath(category.Id);
            }
        }
        public ActionResult ClassifiedList(int id, string seName, int? page)
        {
            var classifieds = new List<ClassifiedAd>();
            var list = new List<string>();
            var _context = new ClassifiedContext();
            BuildCategoryIdPath(id);
            GetLcationId();
            if (CountryId != "")
            {
                BuldLocationByCountryId(CountryId);
            }
            if (curlocationId != "")
            {
                BuildLocationIdPath(curlocationId);
            }
            var category = _classifiedAdCategoryRepository.GetById(id);
            var attr = _categoryAttributeRepository.Filter(x => x.CategoryId == id || x.CategoryId == category.ParentCategoryId).ToList();
            ViewBag.AllList = attr;
            var attributeId = "";
            if (attr.Any())
            {
                foreach (var item in attr)
                {
                    var query = Request.QueryString[item.Attr_Name];
                    if (!string.IsNullOrEmpty(query))
                    {
                        list.Add(query);
                        if (attributeId == "")
                        {
                            attributeId = query;
                        }
                        else
                        {
                            attributeId += "," + query;
                        }
                    }

                }
                ViewBag.Attributes = list;


                ViewBag.ListAttrubute = attributeId;
            }
            classifieds = _classifiedRepository.GetClassifiedAdsByLocationCategoryAttributes(CategoriesId, attributeId, LocationsId);
            ViewBag.CategoryId = id;

            ViewBag.CategoryName = seName;
            var currentPageIndex = page.HasValue ? page.Value - 1 : 0;
            classifieds = classifieds.Where(x => x.IsActive).OrderByDescending(x => x.IsEnhanced).Distinct().ToList();
            return PartialView(classifieds.ToPagedList(currentPageIndex, 8));

        }

        public string getLocation()
        {
            var location = string.Empty; // new Location();
            var currentHost = Request.Url.Host;
            var sub = currentHost.Split('.')[0];

            //if (!Request.IsLocal)
            //{
            if (sub == "www" || sub == domainName || sub == "mail" || sub == "krb3-pc")
            {
            }
            else
            {
                location = sub;
            }

            //}

            return location;
        }




        public string GetCountry()
        {
            var currentlocation = string.Empty;
            if (!Request.IsLocal)
            {
                var ipAddress = Request.UserHostAddress;
                var webservices = new GeoIPService();
                var currentcountry = webservices.GetGeoIP(ipAddress);
                if (currentcountry.ReturnCode == 1)
                    currentlocation = currentcountry.CountryName;
            }
            return currentlocation;
        }
        [HttpPost]
        public ActionResult GetCategoryParent()
        {
            var category = _classifiedAdCategoryRepository.GetMany(x => x.ParentCategoryId == 0).ToList();
            var guid = Guid.NewGuid();
            var data = category.Select(i => new ClassifiedCategory
            {
                Name = i.Name,
                Id = i.Id,

            });
            return Json(new { categoryparent = data, Guid = guid }, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public ActionResult locationHierarchy(string parentId, string id)
        {

            var locationparentId = Convert.ToInt32(parentId);
            var categoryparent = _locationRepository.GetMany(x => x.ParentId == locationparentId).ToList();
            var data = new SelectList(categoryparent, "Id", "Name", id);
            var location = _locationRepository.GetById(x => x.Id == locationparentId);
            var data1 = new Location();
            var guid = Guid.NewGuid();
            if (location != null)
            {
                data1 = new Location
                {
                    ParentId = location.ParentId,
                    Id = location.Id,

                };


            }
            else
            {
                data1 = null;
            }

            return Json(new { selctlist = data, locationparent = data1, Guid = guid }, JsonRequestBehavior.AllowGet);
        }
        [HttpGet]
        public ActionResult Create()
        {
            var current = GetCountry();
            var country = _countryRepository.GetById(x => x.Name.ToLower() == current.ToLower());
            if (country != null)
            {
                ViewBag.Country = new SelectList(_countryRepository.GetAll().OrderBy(x => x.Name), "Id", "Name", country.Id);
                ViewBag.CountryId = Convert.ToString(country.Id);
            }
            else
            {
                ViewBag.Country = new SelectList(_countryRepository.GetAll().OrderBy(x => x.Name), "Id", "Name");
            }
            ViewBag.UserId = new SelectList(_securityService.GetUsers().Where(x => x.IsActive), "Id", "UserName");

            var data = new ClassifiedAd();
            var user = _formsAuthenticationService.GetAuthenticatedUser();
            if (user != null)
            {
                data.EmailID = user.Email;
            }
            data.CreatedOnUtc = DateTime.UtcNow;
            data.UpdatedOnUtc = DateTime.UtcNow;
            data.SubmitDate = DateTime.UtcNow;
            return View(data);
        }
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Create(ClassifiedAd model, List<int> CategoryParent, List<int> locationParent, List<int> AttributName, string option, FormCollection formCollection)
        {
            var attributes = new List<ClassifiedCategoryAttribute>();

            foreach (var i in CategoryParent)
            {

                var data1 = _categoryAttributeRepository.GetMany(
                    x => x.CategoryId == i || x.CategoryId == i).ToList();
                attributes = attributes.Union(data1).ToList();
            }
            var locationId = 0;
            var categoryId = Convert.ToInt32(CategoryParent.LastOrDefault(x => x != 0));
            if (locationParent != null)
            {
                locationId = Convert.ToInt32(locationParent.LastOrDefault(x => x != 0));
            }
            var user = new User();
            var guid = Guid.NewGuid().ToString();
            if (categoryId != 0 && locationId != 0)
            {
                if (ModelState.IsValid)
                {
                    model.SubmitDate = DateTime.UtcNow;
                    model.CreatedOnUtc = DateTime.UtcNow;
                    model.UpdatedOnUtc = DateTime.UtcNow;
                    model.IsActive = false;
                    model.IsEnhanced = false;
                    model.Deleted = false;
                    model.CategoryId = categoryId;

                    var name = User.Identity.Name;
                    if (string.IsNullOrEmpty(name))
                    {
                        user = _securityService.GetUserByEmailId(model.EmailID);
                        if (user == null)
                        {
                            var PW = CryptorEngine.Encrypt(SeService.RandomString(), true);
                            user = new User
                            {
                                DateCreated = DateTime.UtcNow,
                                DateLastActivity = DateTime.UtcNow,
                                DateLastPasswordChange = DateTime.UtcNow,
                                Email = model.EmailID,
                                DateLastLogin = DateTime.UtcNow,
                                IsActive = false,
                                FirstName = model.EmailID,
                                LastName = "",
                                Password = PW,
                                UserName = model.EmailID
                            };
                            _securityService.CreateUser(user);
                            var ver_log = new EmailVerificationlLog()
                            {
                                UserId = user.Id,
                                VerifiedId = guid,
                                CreateDate = DateTime.UtcNow
                            };
                            _verificationlLogRepositories.Add(ver_log);

                            var body =
                "<h1>Classifieds for free.</h1><br/>Congratulations for posting your first ad on Adsx24!<br/>" + model.Title +"<br/>";

                            body += "http://" + cookieDomainName + "/EmailVerified?VR=" + guid;

                            body += "<br/><br/> Thank you for using Adsx24,<br/> <b>The Adsx24 Team</b> ";
                            var objQueuedEmail = new QueuedEmail();
                            bool emailSendStatus = false;
                            emailSendStatus = EmailHelper.SendEmail(AdminEmail, model.EmailID, "Information about your ad:"+ model.Title,
                                                                    body, EmailFrom);


                            if (!emailSendStatus)
                            {
                                objQueuedEmail.SentOnUtc = DateTime.UtcNow;
                                objQueuedEmail.To = model.EmailID;
                                objQueuedEmail.From = AdminEmail;
                                objQueuedEmail.Body = body;
                                objQueuedEmail.CreatedOnUtc = DateTime.UtcNow;
                                objQueuedEmail.FromName = EmailFrom;
                                objQueuedEmail.SentTries = 0;
                                objQueuedEmail.Subject = "Adsx24 Manage your ads - Access your account";
                                objQueuedEmail.IsSent = false;
                                _queuedEmailRepositories.Add(objQueuedEmail);
                            }


                        }
                        
                        
                    }
                    else
                    {
                        model.IsActive = true;
                        user = new User();
                        user = _securityService.GetUserByName(name);


                    }
                    
                    _classifiedRepository.Add(model);
                _securityService.Assignlocations(model.Id, locationId);

                if (user != null)
                {
                    _securityService.AssignUsers(model.Id, user.Id);
                    var verified = _verificationlLogRepositories.GetById(x => x.UserId == user.Id);
                    if (verified == null)
                    {
                   var ver_log = new EmailVerificationlLog()
                        {
                            UserId = user.Id,
                            VerifiedId = guid,
                            CreateDate = DateTime.UtcNow
                        };
                        _verificationlLogRepositories.Add(ver_log);

                    }


                }

                    if (AttributName != null) _securityService.AssignAttributes(model.Id, AttributName);
                    var value = string.Empty;

                    foreach (var items in attributes)
                    {
                        value = formCollection[items.Attr_Name];
                        if (!string.IsNullOrEmpty(value))
                        {
                            var Attr = new ClassifiedAttribute()
                                           {
                                               Attr_Id = items.Id,
                                               ClassifiedId = model.Id,
                                               Value = value
                                           };
                            _clasifiedAttributeRepository.Add(Attr);
                        }

                    }
                    if (option != "Free")
                    {
                        return Content(option + " " + model.Id);
                    }
                    return Content("false");




                }
            }


            ModelState.AddModelError("", "Please select a category.");
            var current = GetCountry();
            var country = _countryRepository.GetById(x => x.Name.ToLower() == current.ToLower());
            if (country != null)
            {
                ViewBag.Country = new SelectList(_countryRepository.GetAll().OrderBy(x => x.Name), "Id", "Name", country.Id);
                ViewBag.CountryId = country.Id;
            }
            else
            {
                ViewBag.Country = new SelectList(_countryRepository.GetAll().OrderBy(x => x.Name), "Id", "Name");
            }

            return Content("Please select a category");

        }
        [Authorize]
        public ActionResult Edit(int id)
        {
            var name = User.Identity.Name;
            var user = _securityService.GetUserByName(name);
            var currentclassified = _classifiedRepository.GetById(id);
            if (currentclassified == null)
                return RedirectToAction("MyAds", "Home");
            if (currentclassified.Users.Count != 0)
            {
                var classifieduser = currentclassified.Users.FirstOrDefault();
                if (classifieduser.UserName != name)
                {
                    return RedirectToAction("MyAds", "Home");
                }
            }
            else
            {
                if (user.Email != currentclassified.EmailID)
                {
                    return RedirectToAction("MyAds", "Home");
                }
            }



            ViewBag.Attributes = _classifiedRepository.AttributeValues();



            var data = _classifiedAdCategoryRepository.GetById(currentclassified.CategoryId);

            ViewBag.AttributeList =
                _categoryAttributeRepository.GetMany(
                    x =>
                    x.CategoryId == data.Id || x.CategoryId == data.ParentCategoryId).ToList();

            ViewBag.Classified_Attr_Textvalue =
                _clasifiedAttributeRepository.GetMany(x => x.ClassifiedId == currentclassified.Id).ToList();

            var currentllocation = currentclassified.Locations.FirstOrDefault();


            if (currentllocation != null)
            {
                ViewBag.locationId = currentllocation.Id;
                ViewBag.locationParentId = currentllocation.ParentId;
                ViewBag.Country = new SelectList(_countryRepository.GetAll().OrderBy(x => x.Name), "Id", "Name", currentllocation.CountryId);
                var currency = _currencyRepository.GetById(x => x.CountryId == currentllocation.CountryId);
                if (currency != null)
                {
                    ViewBag.CurCode = currency.ISO_Code;
                }
            }


            return View(currentclassified);
        }




        //
        // POST: /Admin/Classified/Edit/5

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(ClassifiedAd model, List<int> CategoryParent, List<int> locationParent, List<int> AttributName, string option, FormCollection formCollection)
        {
            var attributes = new List<ClassifiedCategoryAttribute>();
            foreach (var i in CategoryParent)
            {

                var data1 = _categoryAttributeRepository.GetMany(
                    x => x.CategoryId == i || x.CategoryId == i).ToList();
                attributes = attributes.Union(data1).ToList();
            }
            var locationId = 0;
            var categoryId = Convert.ToInt32(CategoryParent.LastOrDefault(x => x != 0));
            if (locationParent != null)
            {
                locationId = Convert.ToInt32(locationParent.LastOrDefault(x => x != 0));
            }

            if (categoryId != 0 && locationId != 0)
            {


                if (ModelState.IsValid)
                {
                    model.SubmitDate = DateTime.UtcNow;
                    model.UpdatedOnUtc = DateTime.UtcNow;
                    model.CategoryId = categoryId;
                    _classifiedRepository.Update(model);
                    if (AttributName != null)
                        _securityService.AssignAttributes(model.Id, AttributName);

                    _securityService.Assignlocations(model.Id, locationId);

                    var value = string.Empty;

                    foreach (var items in attributes)
                    {
                        value = formCollection[items.Attr_Name];
                        if (!string.IsNullOrEmpty(value))
                        {
                            var Attr = new ClassifiedAttribute()
                                           {
                                               Attr_Id = items.Id,
                                               ClassifiedId = model.Id,
                                               Value = value
                                           };
                            _clasifiedAttributeRepository.Add(Attr);
                        }

                    }


                    if (!string.IsNullOrEmpty(option))
                    {
                        if (option != "Free")
                            return Content(option + " " + model.Id);
                    }
                    return Content("false");


                }

            }

            ModelState.AddModelError("", "Please select a category.");
            var currentclassified = _classifiedRepository.GetById(model.Id);
            var currentllocation = currentclassified.Locations.FirstOrDefault();
            ViewBag.Country = new SelectList(_countryRepository.GetAll().OrderBy(x => x.Name), "Id", "Name", currentllocation.CountryId);
            return Content("Please select a category");
        }

        public ActionResult Delete(int id)
        {
            var data = _classifiedRepository.GetById(id);

            if (data != null)
                data.IsActive = false;
            data.IsEnhanced = false;
            data.Deleted = true;
            _classifiedRepository.Update(data);
            return RedirectToAction("MyAds", "Home");
        }


        public PartialViewResult GetCategoryById(int id)
        {

            ViewBag.CategoryName =
                _classifiedAdCategoryRepository.GetById(id).Name;
            var data =
                _classifiedAdCategoryRepository.GetMany(x => x.ParentCategoryId == id);

            return PartialView("_PartialCategoryById", data);
        }
        public PartialViewResult GetAttributelistByid(int id, List<string> filterBy)
        {
            //var check = _classifiedAdCategoryRepository.GetById(x=>x.ParentCategoryId == id || x.SubParentCategoryId == id);
            //if(check !=null)
            //{
            //    return null;
            //}
            ViewBag.CategoryID = id;
            ViewBag.filterBy = filterBy;

            var data = _classifiedAdCategoryRepository.GetById(id);
            ViewBag.CategoryName = data.Name;
            ViewBag.Categories = _classifiedAdCategoryRepository.GetMany(x => x.ParentCategoryId == id).ToList();
            var list =
              _categoryAttributeRepository.Filter(x => x.CategoryId == id || x.CategoryId == data.ParentCategoryId);

            return PartialView("_PartialAttributeslist", list);
        }
        public PartialViewResult ClassifiedComment(int ClassifiedId)
        {
            var comment = new ClassifiedComment();
            comment.ClassifiedId = ClassifiedId;
            return PartialView(comment);
        }

        [HttpPost]
        public ActionResult CreateComment(ClassifiedComment model)
        {

            model.CreateDate = DateTime.UtcNow;
            _classifiedCommentRepository.Add(model);
            var data = _classifiedRepository.GetById(model.ClassifiedId).Title;
            return RedirectToAction("Details", new { id = model.ClassifiedId, seName = data });

        }

        public PartialViewResult CommentList(int classifiedId)
        {
            var comment =
                _classifiedCommentRepository.GetMany(x => x.ClassifiedId == classifiedId).OrderByDescending(
                    x => x.CreateDate).ToList();
            return PartialView(comment);
        }

        [HttpPost]
        public ActionResult UploadImages(int id, IEnumerable<HttpPostedFileBase> attachments)
        {
            var imgGuid = string.Empty;
            var fileName = string.Empty;

            foreach (var file in attachments)
            {
                var fileext = Path.GetExtension(file.FileName);
                if (fileext != ".jpg" && fileext != ".png" && fileext != ".jpeg") continue;
                var coverfilename = Guid.NewGuid() + Path.GetExtension(file.FileName);
                var path = Server.MapPath("~/Content/classified/");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                var finalpath = Path.Combine(path, coverfilename);
                file.SaveAs(finalpath);
                imgGuid = coverfilename;
                fileName = file.FileName;
                var picture = new ClassifiedPicture()
                                  {
                                      Deleted = false,
                                      UploadedOnUtc = DateTime.UtcNow,
                                      ClassifiedId = id,
                                      ImageName = fileName,
                                      ImageGuid = imgGuid

                                  };
                _classifiedPictureRepositories.Add(picture);

            }
            var res = Json(new { guid = imgGuid, filename = fileName });

            return res;

        }

        [HttpPost]
        public ActionResult Remove(string[] fileNames)
        {
            //   var user = _authenticationService.GetAuthenticatedUser();

            foreach (var fileName in fileNames)
            {

                var fullName = Server.MapPath("~/Content/classified/") + Path.GetFileName(fileName);
                var images = _classifiedPictureRepositories.GetMany(x => x.ImageGuid == fileName).FirstOrDefault();
                if (images != null)
                    _classifiedPictureRepositories.Delete(images);
                if (System.IO.File.Exists(fullName))
                {
                    try
                    {
                        System.IO.File.Delete(fullName);
                    }
                    catch (Exception)
                    {
                        //Need to add log in admin reporting
                        throw;
                    }

                }

            }

            var res = Json(new { success = "success" });
            return res;
        }

        [HttpGet]
        public JsonResult GetClassifiedAdsLocations(int Id)
        {
            var data = _locationRepository.GetAll().Where(x => x.IsActive).ToList();
            if (Id == null || Id == 0)
                return Json(data, JsonRequestBehavior.AllowGet);
            var currentdata = _classifiedRepository.GetById(Id);
            foreach (var item in currentdata.Locations)
            {
                data.RemoveAt(data.FindIndex(x => x.Id == item.Id));
            }
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public PartialViewResult ClassifiedAdsPictures(int id)
        {
            var data =
                _classifiedPictureRepositories.GetMany(x => x.ClassifiedId == id && x.Deleted == false).
                    OrderByDescending(x => x.Id).ToList();
            return PartialView(data);
        }

        public ActionResult DeleteClassifiedPicture(int id, int classifiedId)
        {

            var classified = _classifiedRepository.GetById(classifiedId);

            var picture = _classifiedPictureRepositories.GetById(id);
            if (picture.ClassifiedId == classified.Id)
            {
                _classifiedPictureRepositories.Delete(picture);
                var fullName = Server.MapPath("~/Content/classified/") + Path.GetFileName(picture.ImageGuid);
                if (System.IO.File.Exists(fullName))
                {
                    try
                    {
                        System.IO.File.Delete(fullName);
                    }
                    catch (Exception)
                    {
                        //Need to add log in admin reporting
                        throw;
                    }

                }

            }

            return RedirectToAction("Edit", new { id = classifiedId });
        }


        public ActionResult PromoteClassified()
        {
            string autToken = System.Configuration.ConfigurationManager.AppSettings["PDTAuth"].ToString();
            string tx = Request.QueryString["tx"].ToString();

            //build PDT query
            string query = string.Format("cmd=_notify-synch&tx={0}&at={1}", tx, autToken);
            string paypalUrl = System.Configuration.ConfigurationManager.AppSettings["PayPalUrl"].ToString();
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(paypalUrl);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = query.Length;

            //request PDT
            StreamWriter stOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
            stOut.Write(query);
            stOut.Close();

            // get the response
            StreamReader stIn = new StreamReader(req.GetResponse().GetResponseStream());
            string strResponse = stIn.ReadToEnd();
            stIn.Close();



            if (strResponse.StartsWith("SUCCESS"))
            {


                //var user = _authenticationService.GetAuthenticatedUser();
                var payment = new OrderDetail();
                payment.UserId = 0;
                payment.PaidDate = DateTime.Now;

                //try extracting necessary details from the response
                //split the response into string array with whitespace as delimeter
                string[] nvp = strResponse.Split();

                // NOTE:
                /*
                * loop is set to start at 1 rather than 0 because first
                string in array will be single word SUCCESS
                and there is no splitting of this...so we will skip the
                first string and go to the next.
                */

                for (int i = 1; i < nvp.Length; i++)
                {
                    string[] result = nvp[i].Split('=');
                    string sKey = result[0];
                    string sValue = string.Empty;
                    if (result.Length > 1)
                    {
                        sValue = result[1];
                    }

                    switch (sKey)
                    {
                        case "payer_email":
                            payment.PayerEmailId = sValue.Replace("%40", "@");
                            break;

                        case "receiver_email":
                            payment.ReceiverEmailId = sValue.Replace("%40", "@");
                            break;

                        case "mc_gross":
                            payment.Amount = Convert.ToDecimal(sValue);
                            break;

                        case "txn_id":
                            payment.TransactionId = sValue;
                            break;
                        case "item_name":
                            payment.PaymentFor = sValue;
                            break;
                        case "item_number":
                            payment.SelectedId = Convert.ToInt32(sValue);
                            break;
                    }

                }
                _oderDetailRepositories.Add(payment);

                var classified = new ClassifiedAd();

                classified = _classifiedRepository.GetById(x => x.Id == payment.SelectedId);
                classified.IsEnhanced = true;
                _classifiedRepository.Update(classified);

            }
            else
            {
                return View("Error");
            }


            return RedirectToAction("Index", "Home");
        }

        [HttpPost]
        public ActionResult GetPriceShown(string id)
        {
            var categoryId = Convert.ToInt32(id);

            var data = _classifiedAdCategoryRepository.GetById(x => x.Id == categoryId).IsPriceShown;

            return Json(data, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public ActionResult LoadArrtributes(string id)
        {
            var categoryId = Convert.ToInt32(id);
            var list =
                _categoryAttributeRepository.Filter(x => x.CategoryId == categoryId).ToList();
            var data = list.Select(i => new ClassifiedCategoryAttribute
            {
                Id = i.Id,
                Attr_Name = i.Attr_Name,
                Attr_Label = i.Attr_Label,
                AttributeControlTypeId = i.AttributeControlTypeId,
                AttributeValues = i.AttributeValues.Select(x => new AttributeValue
                                                                   {
                                                                       Id = x.Id,
                                                                       Value = x.Value
                                                                   }).ToList()


            });
            return Json(data, JsonRequestBehavior.AllowGet);



        }
        //public ActionResult SearchByAttributes(List<int> AttributesValues)
        //{
        //    var location = string.Empty;
        //    var currentHost = Request.Url.Host;
        //    var sub = currentHost.Split('.')[0];
        //    List<AttributeValue> list = new List<AttributeValue>();
        //    if (AttributesValues != null)
        //    {
        //        foreach (var attributesVlue in AttributesValues)
        //        {
        //            var data = _attributeValueRepository.GetById(attributesVlue);
        //            list.Add(data);
        //        }
        //    }
        //    if (!Request.IsLocal)
        //    {
        //        if (sub == "www" || sub == domainName || sub == "mail")
        //        {
        //        }
        //        else
        //        {
        //            location = sub;
        //        }
        //    }
        //    ViewBag.location = location;
        //    //ViewBag.Attributelist = list.Distinct();
        //    return View(list);

        //}
        public ActionResult ReplyAds(int id)
        {
            var data = _classifiedRepository.GetById(id);
            ViewBag.ClassifiedId = data.Id;
            var QueuedEmail = new QueuedEmail();
            QueuedEmail.To = data.EmailID;
            QueuedEmail.CreatedOnUtc = DateTime.UtcNow;
            return PartialView("_PartialReplyAds", QueuedEmail);
        }
        [HttpPost]
        public ActionResult ReplyAds(QueuedEmail model, int ClassifiedId)
        {
            
            bool emailSendStatus = false;
            emailSendStatus = EmailHelper.SendEmail(model.From, model.To,
                                                    "RepalyAds From "+ model.FromName,
                                                    model.Body, model.FromName);


            if (!emailSendStatus)
            {
                var objQueuedEmail = new QueuedEmail()
                                         {
                                             Body = model.Body,
                                            CreatedOnUtc = DateTime.UtcNow,
                                             From = model.From,
                                             FromName = model.FromName,
                                             IsSent = false,
                                             SentOnUtc = DateTime.UtcNow,
                                             SentTries = 0,
                                             Subject = "RepalyAds From " + model.FromName,
                                             To = model.To
                                         };
                _queuedEmailRepositories.Add(objQueuedEmail);
            }
            var _context = new ClassifiedContext();

            var user = _context.Users.SqlQuery("exec GetUserByClassifiedId @ClassifiedId='" + ClassifiedId + "'").FirstOrDefault();
            var msg = new MessageInfo()
                          {
                              IsRead = false,
                              Body = model.Body,
                              Sender_EmailAddress = model.From,
                              Sender_FullName = model.FromName,
                              SentDate = DateTime.UtcNow,
                              Subject = "RepalyAds From " + model.FromName,
                              UserId = user.Id
                              };
            _messageInfoRepositories.Add(msg);
            return null;
        }
        public ActionResult ClassifiedByUser(int userId)
        {
            var user = _securityService.GetUserById(userId);
            ViewBag.UserName = user.UserName;
            var list = _classifiedRepository.GetClassifiedByUserId(userId);
            return View(list);
        }
        public ActionResult EmailVerified(string VR)
        {
            var log = _verificationlLogRepositories.GetById(x => x.VerifiedId == VR);
            if (log != null)
            {
                var user = _securityService.GetUserById(log.UserId);
                var ads = _classifiedRepository.ClassifiedInActiveByUserId(user.Id);
                foreach (ClassifiedAd classifiedAd in ads)
                {
                   
                    classifiedAd.IsActive = true;

                    _classifiedRepository.Update(classifiedAd);

                }
                FormsAuthentication.SetAuthCookie(user.UserName, false /* createPersistentCookie */);
                return RedirectToAction("MyAds", "Home");
            }

            return RedirectToAction("Index", "Home");
        }

    }
}